﻿using System;
using System.IO;
using System.Net;
using System.Threading;

namespace WebParser
{
    public class HttpContentServer : LoopBased
    {
        public event EventHandler<ContentEventArgs> ContentReceived;
        protected virtual void OnContentReceiver(ContentEventArgs e)
        {
            if (ContentReceived != null) ContentReceived(this, e);
        }
        public event EventHandler<ErrorEventArgs> Error;
        protected virtual void OnError(ErrorEventArgs e)
        {
            if (Error != null) Error(this, e);
        }

        public string Url { get; set; }
        public string Method { get; set; }

        private byte[] _buffer;
        private Stream _stream;
        private HttpContentParser _parser;

        private static WebResponse SendUrlCommand(string urlCommand, string method)
        {
            var request = WebRequest.Create(urlCommand);
            request.Proxy = null;
            request.Method = method;
            return request.GetResponse();
        }
        protected override bool BeforeStart()
        {
            if (string.IsNullOrEmpty(Url) || string.IsNullOrEmpty(Method)) return false;
            try
            {
                _buffer = new byte[0xFFFFFF];
                var r = SendUrlCommand(Url, Method);
                var index = r.ContentType.IndexOf("boundary=");
                if (index < 0) return false;
                _parser = new HttpContentParser("--" + r.ContentType.Substring(index + 9));
                _parser.ContentReceived += (s, e) => OnContentReceiver(e);
                _stream = r.GetResponseStream();
                return _stream != null;
            }
            catch (Exception)
            {
                return false;
            }
        }
        protected override void AfterStart()
        {
            
        }
        protected override void LoopJob()
        {
            //var len = _stream.Read(_buffer, 0, _buffer.Length);
            //for (var i = 0; i < len; i++)
            //    _parser.Parse(_buffer[i]);
            _parser.Parse(_stream);
            Thread.Sleep(1);
        }
        protected override bool BeforeStop()
        {
            return true;
        }
        protected override void AfterStop()
        {
            _stream.Dispose();
        }
    }
}